package cn.pegasus.teamwork.sysconfig.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.iyizhan.teamwork.base.service.impl.BaseServiceImpl;
import cn.pegasus.teamwork.sysconfig.entity.SysConfigFiles;
import cn.pegasus.teamwork.sysconfig.mapper.SysConfigFilesMapper;
import cn.pegasus.teamwork.sysconfig.service.SysConfigFilesService;

/**
 * @author buyuer
 * @version
 */
@Service
public class SysConfigFilesServiceImpl extends BaseServiceImpl<SysConfigFiles, SysConfigFilesMapper> implements SysConfigFilesService {
    // 注入当前dao对象
    @Autowired
    private SysConfigFilesMapper sysConfigFilesMapper;

    public SysConfigFilesServiceImpl() {
        setMapperClass(SysConfigFilesMapper.class, SysConfigFiles.class);
    }

    /*
     * (非 Javadoc) <p>Title: delById</p> <p>Description: </p>
     * 
     * @param id
     * 
     * @see cn.iyizhan.teamwork.sysconfig.service.SysConfigFilesService#delById(java.lang.Integer)
     */
    public void delById(Integer id) {
        SysConfigFiles configFiles = new SysConfigFiles();
        configFiles.setId(id);
        sysConfigFilesMapper.deleteByEntity(configFiles);
    }

    /*
     * (非 Javadoc) <p>Title: queryFiles</p> <p>Description: </p>
     * 
     * @param md5
     * 
     * @return
     * 
     * @see cn.iyizhan.teamwork.sysconfig.service.SysConfigFilesService#queryFiles(java.util.List)
     */
    public List<Map<String, Object>> queryFiles(List<String> md5, Integer appId, Integer fileType ) {
        return sysConfigFilesMapper.queryFiles(md5, appId, fileType);
    }

    /*
     * (非 Javadoc) <p>Title: findByMd5</p> <p>Description: </p>
     * 
     * @param md5
     * 
     * @return
     * 
     * @see cn.iyizhan.teamwork.sysconfig.service.SysConfigFilesService#findByMd5(java.lang.String)
     */
    public SysConfigFiles findByMd5(String md5) {
        SysConfigFiles configFiles = new SysConfigFiles();
        configFiles.setFilesMd5(md5);
        return sysConfigFilesMapper.selectSingle(configFiles);
    }

    public SysConfigFiles detail(SysConfigFiles files) {
        return sysConfigFilesMapper.selectSingle(files);
    }

    /*
     * appPackageName:应用包名
     * appVersion：应用当前的版本
     * appType：0：android   1:ios
     * @see cn.iyizhan.teamwork.sysconfig.service.SysConfigFilesService#queryLastAppVersion(java.lang.String, java.lang.String, java.lang.Integer)
     */
	public Map<String, String> queryLastAppVersion(Map<String, String> reqmap) {
		Map<String, String> map = sysConfigFilesMapper.queryLastAppVersion(
				reqmap.get("appPackageName").toString(),
				reqmap.get("appVersion").toString(), Integer.valueOf(reqmap
						.get("appType").toString()),
				reqmap.get("appVersionCode").toString());
		if (map != null && map.size() > 0) {
			if (Integer.valueOf(map.get("app_version_code").toString()) > Integer.valueOf(reqmap.get("appVersionCode").toString())) {
				map.put("type", "1");
				return map;
			}
		}
		map = new HashMap<String, String>();
		map.put("type", "0");
		return map;
	}
	
	
	public SysConfigFiles getLastAppVersion(Map<String, String> reqmap) {
		SysConfigFiles scf = sysConfigFilesMapper.getLastAppVersion(
				reqmap.get("infoId").toString(), Integer.valueOf(reqmap
						.get("appType").toString()));
		return scf;
	}
    
    
	/**
     * 比较版本
     * @param recentVersion 最新版本
     * @param currentVersion 当前版本
     * @return
     */
    private boolean compareVersion(String recentVersion,String currentVersion){
    	
    	if(StringUtils.isBlank(recentVersion) || StringUtils.isBlank(currentVersion)){
    		
    		return false;
    	}
    	
    	String[] recentArr = recentVersion.split("\\.");
    	String[] currentArr = currentVersion.split("\\.");
    	
    	int len = recentArr.length<currentArr.length?recentArr.length:currentArr.length;
    	
    	for(int i=0;i<len;i++){
    		if(StringUtils.isNumeric(recentArr[i]) && StringUtils.isNumeric(currentArr[i])){
    			if(Integer.valueOf(recentArr[i]).intValue() == Integer.valueOf(currentArr[i]).intValue()){
    				//继续比较
    				continue;
    			}else if(Integer.valueOf(recentArr[i]).intValue() < Integer.valueOf(currentArr[i]).intValue()){
    				//无需更新
    				return false;
    			}else{
    				//提示更新
    				return true;
    			}
    		}else{
    			if(recentArr[i].compareToIgnoreCase(currentArr[i]) == 0){
    				//继续比较
    				continue;
    			}else if(recentArr[i].compareToIgnoreCase(currentArr[i]) < 0){
    				//无需更新
    				return false;
    			}else{
    				//提示更新
    				return true;
    			}
    		}
    	}
    	
    	//如果前面部分都相同,比较数组长度
    	if(recentArr.length<=currentArr.length){
    		//无需更新
			return false;
    	}else{
    		//提示更新
    		return true;
    	}
    }

    /**
	 * 查询最新版本
	 * @param map
	 * @return
	 */
	public SysConfigFiles getNewVersion(Map<String, Object> map) {
		SysConfigFiles scf = new SysConfigFiles();
		List<SysConfigFiles> list = sysConfigFilesMapper.getNewVersion(map);
		if(list!=null&&list.size()>0){
			//最新主版本最大的集合
			List<Integer> newVersionList = newVersionList(list);
			
			//子版本最大的数
			Integer id = newVersionList.get(0);
			for (SysConfigFiles s : list) {
				if(s.getId()==id){
					scf = s;
					break;
				}
			}
			
			//主版本最大相同的 ，比较子版本最大值
			for (int i = 1; i < newVersionList.size(); i++) {
				Integer id1 = newVersionList.get(i);
				for (SysConfigFiles s : list) {
					if(id1==s.getId()){
						if(Integer.parseInt(s.getAppVersionCode())>Integer.parseInt(scf.getAppVersionCode())){
							scf = s;
						}
					}
				}
			}
			
		}
		//返回对象    文件路径和下载地址
		SysConfigFiles result = new SysConfigFiles();
		if(scf.getId()!=null){
			result.setFilesUrl(scf.getFilesUrl());
			result.setDownloadUrl(scf.getDownloadUrl());
		}
		return result;
	}
	
	/**
	 * 最新主版本最大的集合
	 * @param list
	 * @return
	 */
	private List<Integer> newVersionList(List<SysConfigFiles> list){
		List<Map<String,Integer>> splitVersionList = new ArrayList<>();
		//拆分版本   1.0.1
		for (SysConfigFiles obj : list) {
			Map<String,Integer> m = new HashMap<>();
			//保存组件id
			m.put("id", obj.getId());
			//第一个数字
			String strnum1 = obj.getAppVersion().substring(0,obj.getAppVersion().indexOf("."));
			//第一个.后的数字
			String strnum2 = obj.getAppVersion().substring(obj.getAppVersion().indexOf(".")+1,obj.getAppVersion().lastIndexOf("."));
			if(strnum2.length()==1){
				strnum2 = "0"+ strnum2;
			}
			//第二个.后的数字
			String strnum3 = obj.getAppVersion().substring(obj.getAppVersion().lastIndexOf(".")+1);
			if(strnum3.length()==1){
				strnum3 = "0"+ strnum3;
			}
			String str = strnum1 + strnum2 +strnum3;
			m.put("num", Integer.parseInt(str));    //版本1.0.1  -->  1 00 01
			splitVersionList.add(m);
		}
		
		//主版本最大的数
		Map<String,Integer> obj = splitVersionList.get(0);
		//比较大小   取最大的
		for (int i = 1; i < splitVersionList.size(); i++) {
			Map<String,Integer> obj1 = splitVersionList.get(i); 
			if(obj1.get("num")>obj.get("num")){
				obj = obj1;
			}
		}
		
		//最新主版本最大的集合
		List<Integer> newVersionList = new ArrayList<>();
		for (Map<String, Integer> map2 : splitVersionList) {
			if(obj.get("num")==map2.get("num")){
				newVersionList.add(map2.get("id"));
			}
		}
		
		return newVersionList;
	}
}
